package com.example.blogsystemssm.common;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 * 功能：
 *  对登录状态进行确认，假如该Http请求下有合格的session存在，那就正常进行，否则返回401
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * @return true表示拦截器执行（的任务）正常，反之不正常（用户授权失败等情况）
     */
    @Override
    public boolean preHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(Constant.SESSION_USERINFO_KEY) != null) {
            return true;
        }
        response.setStatus(401);
        return false;
    }
}
